package lol.clann.minecraft.springboot.plugin.bukkit.impl.typehandler;

import com.google.auto.service.AutoService;
import com.ruoshui.utils.json.JsonUtils;
import lol.clann.minecraft.springboot.api.bukkit.utils.ItemStackUtils;
import lol.clann.minecraft.springboot.api.spi.mybatis.TypeHandlerProvider;
import lol.clann.minecraft.springboot.bukkit.utils.NMSClasses;
import org.apache.ibatis.type.JdbcType;
import org.bukkit.inventory.ItemStack;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 让mybatis支持ItemStack的持久化
 *
 * @author pyz
 * @date 2019/6/1 3:32 PM
 */
@AutoService(TypeHandlerProvider.class)
public class ItemStackTypeHandler implements TypeHandlerProvider<ItemStack> {
    @Autowired
    private ItemStackUtils itemStackUtils;

    @Override
    public Class<ItemStack> getHandledClass() {
        return ItemStack.class;
    }

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, ItemStack itemStack, JdbcType jdbcType) throws SQLException {
        if (itemStackUtils.isEmpty(itemStack)) {
            preparedStatement.setString(i, null);
            return;
        }

        String json = JsonUtils.writeValueAsString(itemStackUtils.toNBTTagCompound(itemStack));
        preparedStatement.setString(i, json);
    }

    @Override
    public ItemStack getResult(ResultSet resultSet, String s) throws SQLException {
        String json = resultSet.getString(s);
        if (json == null || json.isEmpty()) {
            return null;
        }
        Object tag = JsonUtils.readValue(json, NMSClasses.getNBTTagCompound());
        return itemStackUtils.fromNBTTagCompound(tag);
    }

    @Override
    public ItemStack getResult(ResultSet resultSet, int i) throws SQLException {
        String json = resultSet.getString(i);
        if (json == null || json.isEmpty()) {
            return null;
        }
        Object tag = JsonUtils.readValue(json, NMSClasses.getNBTTagCompound());
        return itemStackUtils.fromNBTTagCompound(tag);
    }

    @Override
    public ItemStack getResult(CallableStatement callableStatement, int i) throws SQLException {
        String json = callableStatement.getString(i);
        if (json == null || json.isEmpty()) {
            return null;
        }
        Object tag = JsonUtils.readValue(json, NMSClasses.getNBTTagCompound());
        return itemStackUtils.fromNBTTagCompound(tag);
    }
}
